from map import *
from snake import *
from food import *
from text import *
from score import *
from endpage import *
import constants
import pygame, sys
from pygame.locals import *
import random

def playPage(screen) :
    Author = TEXT("author : blankspace", AuthorColor, AuthorSize)
    # 音乐
    Channel2.play(playPageBGM)
    # 清图
    screen.fill(backgroundColor)
    Author.printText(AuthorPosition, screen)
    # 地图生成
    mp = MAP(60, 60, 820, 600, 3)
    mp.printMap(screen)
    # 蛇生成
    snack = SNACK(120, 120)
    snack.printSnack(screen)
    # 食物生成
    food = FOOD(mp)
    food.printFood(screen)
    # 文字打印
    text = TEXT("0", scoreColor, scoreSize)
    text.printText(scorePosition, screen)
    # 画面更新
    pygame.display.update()
    
    done = False
    foodExist = True
    score = 0
    while not done :
        # 获取事件
        for event in pygame.event.get() :
            # 退出
            if event.type == pygame.QUIT :
                done = True
            # 键盘事件
            if snack.checkKeydown(event) :
                snack.updateDirection(event)
        # 食物判定
        def eatFood() : return food.pos == snack.head
        if eatFood() :
            foodExist = False
            Channel3.play(foodBGM)
            score += KScore[constants.snakerate]
            text.changeText(str(score))
        # 蛇的位置变更
        snack.updatePosition(foodExist)
        # 更新食物位置
        if not foodExist :
            food = FOOD(mp)
            foodExist = True
        # 碰撞检测
        if snack.checkCollision(mp) :
            done = True
            saveScore(score) # 得分保存
            endPage(screen, score)
            Channel2.stop()
        # 画面更新
        def Update() :
            screen.fill(backgroundColor)
            Author.printText(AuthorPosition, screen)
            
            text.printText(scorePosition, screen)
            mp.printMap(screen)
            food.printFood(screen)
            snack.printSnack(screen)
            pygame.display.update()
        Update()
        # 画面停顿(帧率)
        pygame.time.wait(KSpeed[constants.snakerate])